<template>
  <div class="app-container">
    <!-- 实时数据 -->
    <el-card>
      <live-overview :tabs="realTimeData">
        <div slot="search">
          <p class="mb-5 ft-12">
            <span style="color: #fc4560">*</span>
            <span>默认显示全部，可根据月份进行筛选</span>
          </p>

          <el-form :inline="true" style="display: flex" label-width="100px">
            <el-form-item label="兑换时间：">
              <el-date-picker
                v-model="time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                valueFormat="yyyy-MM-dd"
                style="width: 300px"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="积分来源：">
              <el-select v-model="formOption.platform" placeholder="请选择积分来源">
                <el-option
                  v-for="item in INTEGRAL_RESOURCE"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="客户信息：">
              <ScrollSelect
                placeholder="请选择用户信息"
                :selected-value="formOption.userId"
                :get-list-methods="getListMethods"
                :get-list-format="getListFormat"
                :clearable="true"
                search-key="nickNameOrMobile"
                @selectedChange="selectedChange"
              />
            </el-form-item>

            <el-form-item style="flex: 1; text-align: right">
              <el-button type="primary" @click="search">筛选</el-button>
              <el-button @click="reset">重置</el-button>
              <el-button @click="exportFile">导出</el-button>
            </el-form-item>
          </el-form>
        </div>
      </live-overview>
    </el-card>

    <!-- tabs -->
    <Tabs :tabs="tabs" :currentKey="currentKey" @tab-click="tabClick" />

    <!-- 数据表格 start -->
    <el-card>
      <PageTable
        :loading="loading"
        :data="dataSource"
        :columns="columns"
        :options="options"
        @selectChange="selectChange"
      />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        @pagination="getOverviewDetailStatistics"
      />
    </el-card>
    <!-- 数据表格 end -->
  </div>
</template>

<script>
import _ from 'lodash'
import { export2Excel } from '@/utils/export'
import { useFilterStatistics } from '@/hooks'
import { REGISTER_PLATFORM } from '@/enum/user'
import { INTEGRAL_RESOURCE, EXCHANGE_STATUS, INTEGRAL_PROJECT } from '@/enum/integral'
export default {
  name: 'IntegralOverviewDetail',
  props: {},
  data() {
    return {
      currentKey: 'totalOutlay',
      tabs: [
        {
          key: 'totalOutlay',
          label: '收入',
          num: ''
        },
        {
          key: 'totalIncome',
          label: '支出',
          num: ''
        }
      ],

      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      getListMethods: params => {
        return this.getUserSelectList(params)
      },
      getListFormat: (list = []) => {
        // 下拉框数据格式
        return list.map(({ nickName, mobile, id }) => ({
          label: `${nickName} ${mobile}`,
          value: id
        }))
      },

      // 表格加载
      loading: false,
      // 表格配置
      options: {
        border: true,
        select: true
      },
      dataSource: [],
      realTimeData: [
        {
          isShow: true,
          baseData: {
            key: 'totalOutlayAmount',
            value: '',
            label: '累计总支出积分'
          },
          prompt: {
            showLine: true,
            color: '#409eff',
            text: '平台总支出积分'
          },
          yesterdayData: {
            key: 'yesterdayOutlayAmount',
            isShow: true,
            value: ''
          }
        },
        {
          isShow: true,
          baseData: {
            key: 'totalIncomeAmount',
            value: '',
            label: '累计总收入积分'
          },
          prompt: {
            showLine: true,
            color: '#409eff',
            text: '用户兑换订单总积分'
          },
          yesterdayData: {
            key: 'yesterdayIncomeAmount',
            isShow: true,
            value: ''
          }
        },
        {
          isShow: true,
          baseData: {
            key: 'totalBalance',
            value: '',
            label: '目前剩余总积分'
          },
          prompt: {
            showLine: true,
            color: '#409eff',
            text: '用户账户剩余总积分'
          },
          yesterdayData: {
            key: 'yesterdayBalance',
            isShow: true,
            value: ''
          }
        },
        {
          isShow: true,
          baseData: {
            key: 'giftAmount',
            label: '今日赠送积分',
            value: ''
          }
        },
        {
          isShow: true,
          baseData: {
            key: 'exchangeAmount',
            label: '今日兑换积分',
            value: ''
          }
        }
      ],
      // 表单搜索配置
      formOption: {
        platform: '',
        userId: ''
      },
      time: '',
      selectList: []
    }
  },
  computed: {
    EXCHANGE_STATUS() {
      return EXCHANGE_STATUS
    },
    INTEGRAL_RESOURCE() {
      return INTEGRAL_RESOURCE
    },
    // 表格列
    columns() {
      const arr = [
        { prop: 'id', label: 'ID' },
        {
          label: '会员信息',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.userName}</p>
                <p>{row.userMobile}</p>
              </div>
            )
          }
        },
        {
          prop: 'changeType',
          label: '积分项目',
          render: (h, { row }) => {
            return <div>{INTEGRAL_PROJECT[row.changeType]}</div>
          }
        },
        {
          prop: 'description',
          label: '积分描述',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.description || '/'}</p>
                {row.remark ? (
                  <el-popover placement="bottom" title="查看备注" width="380" trigger="click">
                    <div class="mb-10">{row.remark}</div>
                    <div
                      class="handel flex justify-between"
                      style="padding-top: 10px;border-top: 1px solid #eee"
                    >
                      <p>操作人：{row.createdUser}</p>
                      <p>时间：{row.updatedTime}</p>
                    </div>
                    <el-button slot="reference" underline={false} type="text">
                      查看理由
                    </el-button>
                  </el-popover>
                ) : (
                  ''
                )}
              </div>
            )
          }
        },
        {
          prop: 'amount',
          label: '积分值',
          render: (h, { row }) => {
            return (
              <div>
                <p style={this.currentKey !== 'totalIncome' ? 'color: #409eff' : ''}>
                  <span>{this.currentKey === 'totalIncome' ? '-' : '+'}</span>
                  <span>{row.amount}</span>
                </p>
                {row.isWarning ? (
                  <el-tag size="mini" type="warning" effect="dark">
                    预警
                  </el-tag>
                ) : (
                  ''
                )}
              </div>
            )
          }
        },
        { prop: 'availableBalance', label: '账户余额' },
        { prop: 'createdTime', label: '时间' },
        {
          prop: 'platform',
          label: '来源',
          render: (h, { row }) => {
            return (
              <div>
                <p>{REGISTER_PLATFORM[row.platform]}</p>
                {row.origin === 4 ? <el-button type="primary">查看明细</el-button> : ''}
              </div>
            )
          }
        }
      ]

      if (this.currentKey === 'totalOutlay') {
        return arr
      } else {
        const newArr = _.cloneDeep(arr)
        newArr[2] = {
          prop: 'changeType',
          label: '兑换类型',
          render: (h, { row }) => {
            return <div>{INTEGRAL_PROJECT[row.changeType]}</div>
          }
        }
        newArr.splice(3, 0, {
          prop: 'changeNo',
          label: '关联订单',
          width: '220px',
          render: (h, { row }) => {
            return (
              <div style="color:#409eff">
                <span>订单编号：</span>
                <span class="text-link-blue" onClick={() => this.goToOrderDetail(row.changeNo)}>
                  {row.changeNo}
                </span>
              </div>
            )
          }
        })
        newArr.splice(4, 1)
        return newArr
      }
    }
  },
  created() {
    this.getOverviewDetailStatistics()
  },
  methods: {
    // 切换tab
    tabClick({ key }) {
      this.currentKey = key
      this.listQuery.pageNo = 1
      this.getOverviewDetailStatistics()
    },
    // 获取用户信息
    async getUserSelectList(params) {
      const {
        data: { records }
      } = await this.$http.user.user.getUserSelectList({ params })
      return records
    },
    // 监听选择用户信息
    selectedChange(id) {
      this.formOption.userId = id
    },
    // 获取列表
    async getOverviewDetailStatistics() {
      const params = {
        ...this.formOption,
        ...this.listQuery,
        transactionType: this.currentKey === 'totalOutlay' ? 0 : 1,
        startDate: this.time && this.time[0],
        endDate: this.time && this.time[1]
      }
      const {
        data: {
          total,
          records,
          totalBalance,
          totalIncome,
          totalIncomeAmount,
          totalOutlay,
          totalOutlayAmount,
          yesterdayBalance,
          yesterdayIncomeAmount,
          yesterdayOutlayAmount,
          exchangeAmount,
          giftAmount
        }
      } = await this.$http.integral.overviewDataApi.getOverviewDetailStatistics(params)
      this.total = total
      this.dataSource = records

      // tabs统计
      const tabsKey = {
        totalIncome,
        totalOutlay
      }
      this.tabs = this.tabs.map(item => {
        item.num = tabsKey[item.key]
        return item
      })

      // 实时数据统计
      const integralData = {
        baseData: {
          totalBalance,
          totalOutlayAmount,
          totalIncomeAmount,
          giftAmount,
          exchangeAmount
        },
        yesterdayData: {
          yesterdayBalance,
          yesterdayIncomeAmount,
          yesterdayOutlayAmount
        }
      }
      this.realTimeData = useFilterStatistics(this.realTimeData, integralData)
    },
    // 筛选
    search() {
      this.listQuery.pageNo = 1
      this.getOverviewDetailStatistics()
    },
    // 重置
    reset() {
      this.formOption = {
        platform: '',
        userId: ''
      }
      this.time = ''
      this.listQuery.pageNo = 1
      this.getOverviewDetailStatistics()
    },
    // 导出
    exportFile() {
      if (!this.selectList.length) return this.$message.error('请选择要导出的数据')
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)
      headerData.splice(1, 0, '用户名')
      headerData.splice(2, 0, '手机号码')

      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      filterData.splice(1, 0, 'userName')
      filterData.splice(2, 0, 'userMobile')

      const list = this.$lodash.cloneDeep(this.selectList)
      const tableData = list.map(item => {
        if (item.changeType) {
          item.changeType = INTEGRAL_PROJECT[item.changeType]
        }
        item.platform = REGISTER_PLATFORM[item.platform]
        return item
      })

      let message = this.currentKey === 'totalOutlay' ? '支出' : '收入'

      export2Excel(headerData, tableData, filterData, message, () => {
        this.$message.success('导出成功')
      })
    },
    // 去订单详情
    goToOrderDetail(orderNo) {
      this.$router.push({
        name: 'OrderList',
        query: { orderNo }
      })
    },
    // 列表选择
    selectChange(list) {
      this.selectList = list
    }
  }
}
</script>
